<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodsController extends Controller
{
    private $statusData = [
        1 => '上架中',
        2 => '已下架',
    ];

    /*
     * 列表
     */
    public function lists()
    {
        return view('goods.lists', [
            'statusData' => $this->statusData,
            'goodsTypeData' => $this->goodsTypeData(),
        ]);
    }

    /*
     * 列表
     */
    public function doLists(Request $request)
    {
        $key = $request->input('key', '');
        $goodsType = $request->input('goods_type', ''); //商品类型
        $status = $request->input('status', '0'); //是否下架
//        $page = $request->input('page', '1');
        $pageSize = $request->input('limit', '10');
        $where = [];
        if (!empty($key)) {
            $where[] = ['title', 'like', '%' . $key . '%'];
        }
        if (!empty($goodsType)) {
            $where['goods_type'] = $goodsType;
        }
        if (!empty($status)) {
            $where['status'] = $status;
        }
        //查询账号
        $count = DB::table('goods')->where($where)->count();
        $goods = (array)DB::table('goods')->where($where)->paginate($pageSize)->items();
        $statusData = $this->statusData;
        foreach ($goods as &$value) {
            $value = (array)$value;
            $value['status_str'] = $statusData[$value['status']];
        }
        unset($value);
        return $this->success($goods, '', ['count' => $count, 'statusData' => $statusData]);

    }


    public function goodsTypeData()
    {
        $goodsTypeData = (array)DB::table('goods_type')->get()->map(
            function ($modelValue) {
                return (array)$modelValue;
            }
        )->toArray();
        $goodsTypeData = array_column($goodsTypeData, 'title', 'id');
        return $goodsTypeData;
    }

    public function add()
    {
        return view('goods.add', [
            'statusData' => $this->statusData,
            'goodsTypeData' => $this->goodsTypeData(),
        ]);
    }

    public function doAdd(Request $request)
    {
        $title = $request->input('title', '0');
        $price = $request->input('price', '0');
        $pic = $request->input('pic', '0');
        $number = $request->input('number', '0');
        $goodsType = $request->input('goods_type', '0');
        $date = date('Y-m-d H:i:s', time());
        try {
            if (empty($title)) throw new \Exception("果蔬标题不可以为空");
            if (!is_numeric($price)) throw new \Exception("价格不可以为空");
            if (empty($pic)) throw new \Exception("图片不可以为空");
            if (empty($number)) throw new \Exception("库存不可以为空");
            $data = [
                'title' => $title,
                'price' => $price,
                'pic' => $pic,
                'number' => $number,
                'goods_type' => $goodsType,
                'goods_type_title' => $this->goodsTypeData()[$goodsType],
                'createtime' => $date,
                'updatetime' => $date,
            ];
            $goods = DB::table('goods')->insertGetId($data);
            if (empty($goods)) throw new \Exception("添加果蔬失败");
            $res = DB::table('goods_log')->insertGetId([
                'operator' => session()->get('username', '0'),
                'type_str' => '添加',
                'new_data' => json_encode($data),
                'old_data' => '',
                'createtime' => $date,
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

    public function update(Request $request)
    {
        $id = $request->input('id', '0');
        $goods = (array)DB::table('goods')->where(['id' => $id])->first();
        if (empty($goods)) return redirect('/goods/lists');
        return view('goods.update', [
            'goods' => $goods,
            'goodsTypeData' => $this->goodsTypeData(),
        ]);
    }

    public function doUpdate(Request $request)
    {
        $title = $request->input('title', '0');
        $price = $request->input('price', '0');
        $pic = $request->input('pic', '0');
        $number = $request->input('number', '0');
        $goodsType = $request->input('goods_type', '0');
        $date = date('Y-m-d H:i:s', time());
        try {

            $id = $request->input('id', '0');
            $goods = (array)DB::table('goods')->where(['id' => $id])->first();
            if (empty($goods)) throw new \Exception("修改的蔬果不存在");

            if (empty($title)) throw new \Exception("果蔬标题不可以为空");
            if (!is_numeric($price)) throw new \Exception("价格不可以为空");
            if (empty($pic)) throw new \Exception("图片不可以为空");
            if (empty($number)) throw new \Exception("库存不可以为空");
            $data = [
                'title' => $title,
                'price' => $price,
                'pic' => $pic,
                'number' => $number,
                'goods_type' => $goodsType,
                'goods_type_title' => $this->goodsTypeData()[$goodsType],
                'updatetime' => $date,
            ];
            $goods = DB::table('goods')->where(['id' => $id])->update($data);
            if (empty($goods)) throw new \Exception("修改果蔬失败");
            $res = DB::table('goods_log')->insertGetId([
                'operator' => session()->get('username', '0'),
                'type_str' => '修改',
                'new_data' => json_encode($data),
                'old_data' => json_encode($goods),
                'createtime' => $date,
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($goods);
    }

    public function status(Request $request)
    {
        try {
            $status = $request->input('status', '0');
            if (empty($this->statusData[$status])) throw new \Exception("状态不对");
            $id = $request->input('id', '0');
            $goods = (array)DB::table('goods')->where(['id' => $id])->first();
            if (empty($goods)) throw new \Exception("修改的蔬果不存在");
            $goods = DB::table('goods')->where(['id' => $id])->update(['status' => $status]);
            if (empty($goods)) throw new \Exception("修改果蔬失败,刷新后重试");
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($goods);
    }

    public function del(Request $request)
    {
        try {
            $ids = $request->input('ids', '0');
            if (empty($ids)) throw new \Exception("删除失败");
            if (!is_array($ids)) {
                $ids = [$ids];
            }
            $res = DB::table('goods')->whereIn('id', $ids)->delete();
            $res = DB::table('cart')->whereIn('goods_id', $ids)->delete();
            $date = date('Y-m-d H:i:s', time());
            $res = DB::table('goods_log')->insertGetId([
                'operator' => session()->get('username', '0'),
                'type_str' => '删除',
                'new_data' => json_encode($ids),
                'old_data' => '',
                'createtime' => $date,
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

}